<template>
    <v-overlay persistent class="recharge-overlay">
        <v-row class="recharge-card-main">
            <div
                    class="recharge-protocol-box d-flex justify-center"
                    v-if="isShowProtocol"
            >
                <!-- 用户协议 -->
                <div class="recharge-protocol-container">
                    <div class="recharge-card-header">
                        <v-spacer></v-spacer>

                        <div
                                class="close"
                                @click="handleClose"
                                :class="{ 'is-recharge': !isShowProtocol }"
                                v-if="isShowProtocol"
                        >
                            <i class="el-icon-close"></i>
                        </div>
                    </div>

                    <v-col class="recharge-protocol">
                        <div class="recharge-protocol-title">
                            请阅读一下协议并勾选同意，然后点击按钮前往充值。
                        </div>

                        <v-row v-for="item in list" :key="item.title">
                            <v-col cols="12">
                                <el-checkbox v-model="item.value">{{ item.title }}</el-checkbox>
                            </v-col>
                        </v-row>

                        <div style="text-align: center; margin-top: 1rem">
                            <v-btn
                                    variant="outlined"
                                    color="#FFF"
                                    @click="handleClickProtocolButton"
                            >我知道了
                            </v-btn
                            >
                        </div>
                    </v-col>
                </div>
            </div>

            <v-col cols="12" v-else>
                <v-card
                        :color="isShowSuccessTip ? '#333030' : '#000'"
                        max-width="1200px"
                        style="margin: 0 auto"
                >
                    <div class="pa-5" style="overflow: hidden auto; max-height: 100vh">
                        <div class="d-flex">
                            <div class="d-flex align-center" style="width: 100%">
                                <div class="text-h5 text-white">账户充值</div>
                                <v-spacer></v-spacer>
                                <div class="close" @click="handleClose">
                                    <i class="el-icon-close"></i>
                                </div>
                            </div>
                        </div>

                        <v-row v-show="!isShowSuccessTip" dense>
                            <v-col cols="12 recharge-left" md="7">
                                <div class="my-4">
                                    <v-row>
                                        <v-col
                                                v-for="(item, index) in price"
                                                cols="3"
                                                md="3"
                                                :key="item"
                                        >
                                            <v-btn
                                                    block
                                                    class="text-white"
                                                    :color="item === amount ? '#6C79D8' : '#13161b'"
                                                    depressed
                                                    outlined
                                                    :disabled="tabs === 'cdk'"
                                                    @click="
                          setAmount(item, index);
                          getRecharge();
                        "
                                            >￥{{ item }}
                                            </v-btn
                                            >
                                        </v-col>
                                    </v-row>
                                </div>

                                <v-row class="recharge-tip">
                                    <div class="recharge-tip-content">
                                        <img src="../../static/img/icon/warn.png" alt/>
                                        <div>
                                            网站服务不满意，可加群联系客服，可以解决所有问题。
                                            <br/>注意：如若出现电子游戏成瘾情况，可联系客服请求帮助，理性消费，娱乐为主
                                        </div>
                                    </div>
                                </v-row>
                            </v-col>

                            <v-col class="recharge-card-pay" cols="12" md="5">
                                <el-tabs v-model="tabs" @tab-click="getRecharge">
<!--                                    <el-tab-pane label="支付宝" name="rxka-ali"></el-tab-pane>-->
                                    <el-tab-pane label="支付宝新" name="fuxinka"></el-tab-pane>
                                    <el-tab-pane label="支付宝2" name="jiujia"></el-tab-pane>
<!--                                    <el-tab-pane label="微信" name="wx_lite"></el-tab-pane>-->
                                    <el-tab-pane label="CDK兑换" name="cdk"></el-tab-pane>
                                </el-tabs>

                                <v-row v-if="tabs !== 'cdk'">
                                    <v-col cols="12" class="text-white" style="font-size: 13px">
                                        <p>实付金额： ￥{{ amount }}</p>
                                        <div v-if="amountObj.coin_total">获得{{amountObj.coin_total}}硬币
                                        <span v-if="amountObj.coin_give">(赠送{{amountObj.coin_give}})</span>
                                        </div>
                                        <p style="color: #f09116">
                                            温馨提示:支付到账有几秒延迟,请耐心等待
                                        </p>
                                    </v-col>
                                    <v-col cols="12">
                                        <div class="qr-code-wrapper" :class="[tabs === 'wx_lite' ? '':'']" v-loading="loading">
                                            <template v-if="qrCode">
                                                <img
                                                        v-if="tabs === 'alipay'"
                                                        style="width: 100%; height: 100%"
                                                        :src="qrCode"
                                                        alt=""
                                                />
                                                <vue-qrcode v-else :value="qrCode"></vue-qrcode>
                                            </template>
                                            <template v-else>
                                                <p v-show="!loading && !error">请选择充值金额</p>
                                                <v-btn
                                                        v-show="error"
                                                        variant="outlined"
                                                        color="#E0F7FA"
                                                        @click="handleRetry"
                                                >重试
                                                </v-btn
                                                >
                                            </template>
                                        </div>
                                    </v-col>

                                    <v-col cols="12">
                                        <p
                                                v-show="tabs === 'wx_lite'"
                                                style="color: rgb(240, 145, 22)"
                                                class="mb-1"
                                        >
                                            微信支付请直接用微信扫描二维码进行充值，不支持识别相册截图
                                        </p>
                                        请使用
                                        <span style="color: #f09116"
                                        >"{{ tabs === "wx_lite" ? "微信" : "支付宝" }}扫一扫"</span
                                        >
                                        完成支付
                                        <br/>(请在两分钟内支付)
                                    </v-col>
                                </v-row>

                                <!-- cdk -->
                                <v-row v-else>
                                    <v-col cols="12">
                                        <el-input
                                                placeholder="请输入卡号"
                                                v-model="cdk.form.card_no"
                                                clearable
                                        ></el-input>
                                    </v-col>
                                    <v-col cols="12">
                                        <el-input
                                                placeholder="请输入卡密码"
                                                v-model="cdk.form.card_secret"
                                                clearable
                                        ></el-input>
                                    </v-col>
                                    <v-col cols="12">
                                        <span class="text-red">友情提示：CDK使用一次后作废，请妥善保管。若出现问题请联系管理员。</span>
                                    </v-col>
                                    <v-col cols="12">
                                        <v-btn color="primary" :loading="cdk.loading" @click="handleCdkRecharge">确认充值
                                        </v-btn>
                                    </v-col>
                                </v-row>
                            </v-col>
                        </v-row>

                        <el-result icon="success" v-show="isShowSuccessTip">
                            <template #title>
                                <span class="text-white" style="font-size: 16px">充值成功</span>
                            </template>
                            <template #extra>
                                <el-button
                                        type="text"
                                        style="color: rgb(240, 145, 22)"
                                        @click="handleBack"
                                >继续充值
                                </el-button
                                >
                                <v-btn
                                        class="ml-5 text-white"
                                        variant="outlined"
                                        @click="handleClose"
                                >关闭
                                </v-btn
                                >
                            </template>
                        </el-result>
                    </div>
                </v-card>
            </v-col>
        </v-row>
    </v-overlay>
</template>

<script lang="ts">
    import {reactive, ref, toRefs, watch} from "vue";
    import {PaymentService} from "@/services/PaymentService";
    import {isMobile} from "@/utils";
    import {store} from "@/store";

    export default {
        name: "recharge-card",

        setup() {
            const price = [30, 50, 100, 200, 500, 1000, 2000];
            const setAmount = (amount, index) => {
                state.amount = amount;
                state.priceIndex = index;
            };
            const state = reactive({
                price,
                tabs: "fuxinka",
                qrCode: "",
                amount: 0,
                isShowProtocol: true,
                loading: false,
                error: false,
                // 充值成功标识
                isShowSuccessTip: false,
                priceIndex: -1,
                // 二维码缓存
                qrCodeCache: [] as {
                    qrcode: string;
                    amount: number;
                    method: string;
                    order_no: string;
                }[],
                cdk: {
                    loading: false,
                    form: {
                        card_no: "",
                        card_secret: "",
                    },
                },
                amountObj:{}
            });
            watch(() => state.amount, (newVal) => {
                if(newVal > 0){
                    reduceAmount(newVal)
                }
            })
            function reduceAmount(amount) {
                PaymentService.calculateRecharge({
                    amount:amount
                }).then(res =>{
                   if(res.data.code == 0){
                       state.amountObj = res.data.data
                   }
                })
            }
            return {
                ...toRefs(state),
                setAmount,
                list: ref(
                    [
                        "1.我满18岁且具备完全行为能力。",
                        "2.购买虚拟物品后不可退款或者换货。",
                        "3.取回为第三方发货，通常12H以内发货。",
                        "4.请在经济承受能力内进行消费。",
                    ].map((title) => ({
                        value: true,
                        title,
                    }))
                ),
                goodsIds: [32753, 32757, 32758, 32759, 32760, 32761, 32762],
            };
        },

        methods: {
            handleClickProtocolButton() {
                for (let i = 0; i < this.list.length; i++) {
                    if (!this.list[i].value) {
                        this.$notify.warning("请先阅读以下协议并勾选同意");
                        return;
                    }
                }

                this.isShowProtocol = false;
            },
            handleRetry() {
                this.error = false;
                this.getRecharge();
            },

            cleanQrCodeCache() {
                this.qrCodeCache = [];
            },

            handleClose() {
                this.clearOrderDetailTimer();
                this.cleanQrCodeCache();
                this.$emit("close");

                setTimeout(() => {
                    this.isShowProtocol = true;
                    this.loading = false;
                    this.error = false;
                    this.qrCode = "";
                    this.amount = 0;
                    this.isShowSuccessTip = false;
                    this.clearCdk();
                    this.tabs = "fuxinka";

                    for (let i = 0; i < this.list.length; i++) {
                        this.list[i].value = true;
                    }
                }, 300);
            },

            checkOrder(order_no: string) {
                this.clearOrderDetailTimer();
                let timerStartTime = Date.now();
                this.checkOrderTimer = setInterval(() => {
                    PaymentService.getOrderDetail(order_no).then((res) => {
                        const {pay_status} = res.data.data;
                        if (pay_status === 1) {
                            this.$store.dispatch("getUserInfo");
                            this.$notify.success("充值成功");
                            this.clearOrderDetailTimer();
                            this.isShowSuccessTip = true;
                            this.cleanQrCodeCache();
                        } else {
                            if (Date.now() - timerStartTime > 1000 * 60 * 6) {
                                // 超出六分钟 停止检查订单
                                this.clearOrderDetailTimer();
                            }
                        }
                    });
                }, 2000);
            },

            clearOrderDetailTimer() {
                clearInterval(this.checkOrderTimer);
                this.checkOrderTimer = null
            },

            setRechargeCache(order_no: string) {
                this.qrCodeCache.push({
                    amount: this.amount,
                    method: this.tabs,
                    order_no,
                    qrcode: this.qrCode,
                });
            },

            getRechargeCache() {
                return this.qrCodeCache.find((item) => {
                    return item.amount === this.amount && item.method === this.tabs;
                });
            },

            deleteRecahrgeCache(order_no: string) {
                this.qrCodeCache = this.qrCodeCache.filter(
                    (item) => item.order_no !== order_no
                );
            },
            getRecharge() {
                if (this.tabs === "cdk") return;
                this.qrCode = "";
                this.loading = false;
                const qrCodeCache = this.getRechargeCache();
                if (qrCodeCache) {
                    this.qrCode = qrCodeCache.qrcode;
                    this.checkOrder(qrCodeCache.order_no);
                    return;
                }
                //微信支付
                if (this.tabs == 'wx_lite' && this.amount) {
                    this.loading = true;
                    PaymentService.makeOrder(
                        {
                            channel: 'adapay',
                            method: 'wx_lite',
                            amount: this.amount,
                            subject: '',
                            body: '',
                        }
                    ).then(res =>{
                        if(res.data.code == 0){
                            const token = store.state.token || localStorage.getItem("token");
                            let baseUrl = import.meta.env.VITE_BASE_URL as string;
                            const {appId, orderNo:order_no,payUrl} = res.data.data;
                            // this.qrCode = `${baseUrl}/adapay/wxpay.html?token=` + token + '&appId=' + appId + '&order_no=' + order_no + '&baseUrl=' + baseUrl
                            this.qrCode = payUrl
                            if (order_no) {
                                this.checkOrder(order_no);
                            }
                            this.setRechargeCache(order_no);
                        }
                        this.loading = false;
                    })
                    return;
                }

                //支付宝
                if (this.amount) {
                    this.loading = true;
                    const method = this.tabs;
                    if(method == 'fuxinka'){
                        PaymentService.getAlipayFuxinka({
                            amount: this.amount,
                            pay_type:'alipaywap'
                        }).then(res=>{
                            const {qrcode, order_no} = res.data.data;
                            this.qrCode = qrcode;
                            if (order_no) {
                                this.checkOrder(order_no);
                            }
                            this.setRechargeCache(order_no);
                        })
                            .catch((response) => {
                                this.error = true;
                            })
                            .finally(() => {
                                this.loading = false;
                            });
                    }else{
                        PaymentService.payment({
                            channel: method == 'rxka-ali' ? 'adapay':'jiujia',
                            method: method == 'rxka-ali' ? 'alipay_wap':'alipay',
                            amount: this.amount,
                            subject: '',
                            body: '',
                        })
                            .then((res) => {
                                if (method === this.tabs) {
                                    const {url, order_no} = res.data.data;
                                    this.qrCode = url;
                                    if (order_no) {
                                        this.checkOrder(order_no);
                                    }
                                    this.setRechargeCache(order_no);
                                }
                            })
                            .catch((response) => {
                                this.error = true;
                            })
                            .finally(() => {
                                this.loading = false;
                            });
                    }
                }
            },

            handleBack() {
                this.isShowSuccessTip = false;
                this.cleanQrCodeCache();
            },

            handleCdkRecharge() {
                let {card_no, card_secret} = this.cdk.form;
                card_no = card_no.trim();
                card_secret = card_secret.trim();
                if (!card_no) {
                    this.$notify.warning("请输入卡号");
                    return;
                }
                if (!card_secret) {
                    this.$notify.warning("请输入卡密");
                    return;
                }
                this.cdk.loading = true;
                PaymentService.cdkRecharge(this.cdk.form).then(() => {
                    this.$store.dispatch("getUserInfo");
                    this.clearCdk();
                    this.isShowSuccessTip = true;
                }).finally(() => {
                    this.cdk.loading = false;
                })
            },

            clearCdk() {
                this.cdk.form.card_no = "";
                this.cdk.form.card_secret = "";
                this.cdk.loading = false;
            }
        },

        unmounted() {
            this.clearOrderDetailTimer();
        },
    };
</script>

<style lang="scss">
    .recharge-card-pay {
        color: #fff;
        text-align: center;
        font-size: 13px;

        .el-tabs__nav-wrap {
            &:after {
                background: #242a33;
            }
        }

        .el-tabs__item {
            font-size: 16px;
            color: #fff;
        }
    }

    .recharge-card-main {
        position: relative;
        min-width: 60%;
        max-width: 93%;
        max-height: 100%;
        overflow-x: hidden;
        overflow-y: auto;
        box-sizing: border-box;

        .recharge-card-header {
            display: flex;
            justify-items: flex-end;
            width: 100%;
        }
    }

    .close {
        width: 36px;
        height: 36px;
        background: rgba(255, 255, 255, 0.1);
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        z-index: 1;

        &:hover {
            background: rgba(255, 255, 255, 0.2);
        }

        &.is-recharge {
            margin-right: 12px;
        }

        i {
            color: #fff;
            font-size: 20px;
        }
    }

    .recharge-protocol {
        background: #36363c;
        padding: 2rem;
        overflow: hidden;

        .recharge-protocol-title {
            color: #fff;
            margin: 1rem 0;
            text-align: center;
            font-size: 13px;
        }
    }

    .qr-code-wrapper {
        width: 160px;
        height: 160px;
        display: flex;
        justify-content: center;
        align-items: center;
        margin: 0 auto;
        border: 1px solid rgba(255, 255, 255, 0.6);
        background: #252b34;
        border-radius: 2px;
    }
    .qr-code-wrapper-wx{
        width: 260px;
        height: 260px;
    }
    .recharge-left {
        display: flex;
        flex-direction: column;
        justify-content: space-between;

        > * {
            flex: none;
        }

        .recharge-tip {
            color: #fff;
            font-size: 12px;
            padding-left: 6px;
            line-height: 20px;
            box-sizing: border-box;
            display: flex;
            align-items: flex-end;
            color: #7f7f7f;

            .recharge-tip-content {
                display: flex;
                align-items: center;

                img {
                    width: 2rem;
                    height: 2rem;
                    margin-right: 10px;
                }
            }
        }
    }

    .recharge-overlay .v-overlay__content {
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    @media screen and (max-width: 768px) {
        .recharge-card-main {
            max-width: 93%;
        }
    }

    .recharge-protocol-box {
        width: 100%;

        .recharge-protocol-container {
            width: 100%;
            max-width: 500px;
        }
    }
</style>
